package com.wb.mas.ui.auth;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wb.mas.BR;
import com.wb.mas.BuildConfig;
import com.wb.mas.R;
import com.wb.mas.app.AppViewModelFactory;
import com.wb.mas.app.Constants;
import com.wb.mas.databinding.ActAuthBankCardBinding;
import com.wb.mas.entity.AuthBackResponse;
import com.wb.mas.entity.DicInfoEntity;
import com.wb.mas.widget.OnPopitemClickLinstener;
import com.wb.mas.widget.SelectPopWindow;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ImageUtils;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthBankCardAc extends BaseActivity<ActAuthBankCardBinding, AuthBankViewModel> implements OnPopitemClickLinstener {
    public static final int TAKE_PHOTO_REQUEST_CODE1 = 101;
    private static final String TAG = AuthBankCardAc.class.getSimpleName();
    private Uri mImageUri;
    private static final String FILE_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID+".fileprovider";


    private SelectPopWindow selectPopWindow;
    private File imageFile;


    @Override
    public AuthBankViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(AuthBankViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.act_auth_bank_card;
    }

    @Override
    public int initVariableId() {
        return BR.authBankViewModel;
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();


        viewModel.uc.takePicEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {

                requestCameraPermissions(TAKE_PHOTO_REQUEST_CODE1);
            }
        });

        viewModel.uc.selectBankEvent.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                showDictPopUpWindow(viewModel.getCurrentDictType(), viewModel.getCurrentDictList());

            }
        });


    }

    /**
     * 请求相机权限
     */
    private void requestCameraPermissions(final int takePhotoRequestCode) {
        //请求打开相机权限
        RxPermissions rxPermissions = new RxPermissions(AuthBankCardAc.this);
        rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            doTakePhoto(takePhotoRequestCode);
                        } else {
                            ToastUtils.showShort("权限被拒绝");
                        }
                    }
                });
    }


    public void doTakePhoto(int requestCode) {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {//这句作用是如果没有相机则该应用不会闪退，要是不加这句则当系统没有相机应用的时候该应用会闪退
            //创建用来保存照片的文件
            imageFile = createImageFile();
            if (imageFile != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    /*7.0以上要通过FileProvider将File转化为Uri*/
                    mImageUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, imageFile);
                } else {
                    /*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
                    mImageUri = Uri.fromFile(imageFile);
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//将用于输出的文件Uri传递给相机
                startActivityForResult(takePhotoIntent, requestCode);//打开相机
            }
        }
    }


    /**
     * 创建用来存储图片的文件，以时间来命名就不会产生命名冲突
     *
     * @return 创建的图片文件
     */
    private File createImageFile() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageFile;
    }


    private void showDictPopUpWindow(String currentDictType, List<DicInfoEntity> currentDictList) {
        String titleName = getPopTitleName(currentDictType);
        List<String> itemStrList = new ArrayList<>();
        for (DicInfoEntity entity : currentDictList) {

            itemStrList.add(entity.getDictValue());
        }
        getPopUpWindow(itemStrList, titleName).show(this, itemStrList.get(0));
    }

    private String getPopTitleName(String currentDictType) {
        return getString(R.string.auth_pi_please_select_hint);
    }


    private SelectPopWindow getPopUpWindow(List<String> itemStrList, String titleName) {
//        if (selectPopWindow == null) {
        selectPopWindow = new SelectPopWindow(this, itemStrList, titleName);

        selectPopWindow.setOnPoPItemClickLinstener(this);
//        } else {
//        }

        return selectPopWindow;
    }

    @Override
    public void OnItemClick(String title, int position) {

        viewModel.onItemSelected(title, position);
        selectPopWindow.dismiss();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if ((requestCode == TAKE_PHOTO_REQUEST_CODE1) && resultCode == RESULT_OK) {
            try {
                /*如果拍照成功，将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImageUri));
                if (requestCode == TAKE_PHOTO_REQUEST_CODE1) {
                    doUploadImg(mImageUri, imageFile, Constants.FILE_TYPE_OF_13);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


    private void doUploadImg(final Uri mImageUri, File imageFile, final String fileType) {
        if (mImageUri == null) {
            KLog.e(TAG, "mImageUri is null");
            return;
        }
        KLog.e(TAG, "mImageUri's path is:" + mImageUri.getPath());

        showDialog();

        ImageUtils.compressWithRx(imageFile.getAbsolutePath(), new Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                dismissDialog();
                if (o instanceof File) {

                    File photoFile = (File) o;
                    if (Constants.FILE_TYPE_OF_13.equals(fileType)) {
                        AuthBackResponse.DataBean.BankCardImagesBean identityImagesBean = new AuthBackResponse.DataBean.BankCardImagesBean();
                        identityImagesBean.setLocalPath(photoFile.getAbsolutePath());
                        identityImagesBean.setFileType(Integer.parseInt(Constants.FILE_TYPE_OF_13));
                        viewModel.idCardPositiveBean.set(identityImagesBean);

                    }
                    viewModel.doUploadImg(mImageUri, photoFile, fileType);
                }

            }
        });

    }

}
